package handler

import (
	"exam-app/api/global"
	"exam-app/api/internal/request"
	"exam-app/api/tools"
	pb "exam-app/user-srv/proto"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Login(c *gin.Context) {
	var req request.LoginReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "参数获取失败"})
		return
	}
	login, err := global.UserClient.Login(c, &pb.LoginRequest{
		Account:  req.Account,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "登录失败" + err.Error()})
		return
	}
	claims := tools.CustomClaims{
		ID:             uint(login.Id),
		StandardClaims: jwt.StandardClaims{ExpiresAt: 604800},
	}
	newJWT := tools.NewJWT("abc")
	token, err := newJWT.CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "token创建失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "message": "登录成功", "token": token})
}
